<template>
  <div class="chat-page">
    <div class="chat-container layout-two-col">
      <!-- 左侧会话列表 -->
      <div class="chat-sidebar panel">
        <div class="sidebar-header panel__header">
          <el-button type="primary" class="new-chat-btn" @click="createNewChat">
            <el-icon><Plus /></el-icon>
            新建对话
          </el-button>
        </div>

        <div class="session-list panel__body--scroll">
          <div v-for="session in sessions" :key="session.id" class="session-item" :class="{ active: currentSessionId === session.id }" @click="switchSession(session.id)">
            <div class="session-avatar">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="session-content">
              <div class="session-title">{{ session.title }}</div>
              <div class="session-preview">{{ session.lastMessage }}</div>
            </div>
            <div class="session-actions">
              <div class="session-time">{{ formatTime(session.updatedAt) }}</div>
              <el-button type="text" size="small" circle @click.stop="deleteSessionHandler(session.sessionId)" class="delete-btn" :title="'删除会话'">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧聊天区域 -->
      <div class="chat-main panel">
        <!-- 消息列表 -->
        <div class="chat-content">
          <!-- 空状态 -->
          <div v-if="chatMessages.length === 0" class="empty-state">
            <div class="welcome-container">
              <div class="ai-avatar">
                <el-icon><ChatDotRound /></el-icon>
              </div>
              <h2 class="welcome-title">欢迎使用AI助手</h2>
              <p class="welcome-subtitle">我可以帮助您解答问题、编写代码、分析内容等</p>
              <div class="quick-actions">
                <div v-for="action in quickActions" :key="action.text" class="quick-action-card" @click="handleQuickAction(action)">
                  <div class="action-icon">
                    <el-icon><component :is="action.icon" /></el-icon>
                  </div>
                  <span class="action-text">{{ action.text }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 消息列表 -->
          <div v-else class="messages-area" ref="messageListRef" v-auto-scroll:bottom>
            <div v-for="(message, index) in chatMessages" :key="`msg-${index}`" class="message-wrapper" :class="message.role">
              <div class="message-bubble">
                <!-- 用户消息 -->
                <div v-if="message.role === 'human'" class="message-text user-message">
                  {{ message.content }}
                </div>

                <!-- AI消息使用安全的MdPreview渲染Markdown -->
                <div v-else class="message-text ai-message">
                  <SecureMdPreview
                    :modelValue="message.content"
                    :theme="'light'"
                    :showCodeRowNumber="true"
                    :previewTheme="'github'"
                    :codeTheme="'github'"
                    style="padding: 0; background-color: transparent; width: 100%"
                  />
                </div>

                <div class="message-time">{{ formatTime(message.time) }}</div>
              </div>
            </div>

            <!-- 打字机效果占位符 -->
            <div v-if="isLoading && messagePlaceholder" class="message-wrapper system">
              <div class="message-bubble typing">
                <div class="message-text ai-message">
                  <SecureMdPreview
                    :modelValue="messagePlaceholder"
                    :theme="'light'"
                    :showCodeRowNumber="true"
                    :previewTheme="'github'"
                    :codeTheme="'github'"
                    style="padding: 0; background-color: transparent; width: 100%"
                  />
                </div>
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部输入区 -->
        <div class="chat-footer panel__footer">
          <div class="input-area">
            <div class="input-wrapper">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="1"
                :autosize="{ minRows: 1, maxRows: 4 }"
                placeholder="输入消息... (Shift + Enter 换行 / Ctrl 或 Cmd + Enter 发送)"
                class="message-input"
                @keydown="handleKeydown"
                @compositionstart="isComposing = true"
                @compositionend="isComposing = false"
                :disabled="isLoading"
              />
              <el-button type="primary" circle class="send-button" :disabled="!inputMessage.trim() || isLoading" @click="sendMessage">
                <el-icon><Top /></el-icon>
              </el-button>
            </div>
          </div>
          <div class="input-footer">
            <span class="disclaimer">AI生成的内容，仅供参考</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, reactive, ref } from "vue"
import { deleteSession, getChatMessages, getUserSessions, sendMessage as apiSendMessage } from "@/api/modules/chat"
import { useUsersStore } from "@/stores/modules/user"
import { ElMessage } from "element-plus"
import { ChatDotRound, Delete, Document, List, Monitor, Plus, Top, User } from "@element-plus/icons-vue"
// 导入安全的MdPreview组件
import SecureMdPreview from "@/components/common/secureMdPreview.vue"

// 自动滚动指令
const autoScrollDirective = {
  updated(el, binding) {
    if (binding.arg === "bottom" && el.lastElementChild) {
      nextTick(() => {
        el.scrollTop = el.scrollHeight
      })
    }
  }
}

// 注册指令
const vAutoScroll = autoScrollDirective

// 响应式数据
const chatMessages = ref([])
const inputMessage = ref("")
const isLoading = ref(false)
const messageListRef = ref(null)
const messagePlaceholder = ref("") // 打字机占位符
const currentSessionId = ref(null)
const isComposing = ref(false)
const canSend = computed(() => inputMessage.value.trim().length > 0 && !isLoading.value)
const usersStore = useUsersStore()

// 真实会话数据
const sessions = ref([])
const loadingSessions = ref(false)

// 快捷操作（使用组件引用而不是字符串）
const quickActions = reactive([
  { text: "代码优化", icon: Monitor, prompt: "请帮我优化以下代码：" },
  { text: "问题解答", icon: Document, prompt: "我有一个问题想请教：" },
  { text: "内容分析", icon: List, prompt: "请帮我分析以下内容：" },
  { text: "角色扮演", icon: User, prompt: "现在你将扮演一个专家，与我进行对话：" }
])

// 预处理Markdown内容，确保格式正确
const processMarkdownContent = content => {
  if (!content) return ""

  try {
    // 确保#标题后有空格
    content = content.replace(/^(#+)([^\s])/gm, "$1 $2")

    // 确保代码块正确渲染
    content = content.replace(/```(\w*)\n/g, "```$1\n")

    // 修复表格语法
    content = content.replace(/\|[\s-]+\|/g, match => {
      if (!/\|-+\|/.test(match)) {
        return match.replace(/\s+/g, "-")
      }
      return match
    })

    return content
  } catch (e) {
    return content
  }
}

// 发送消息方法
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  inputMessage.value = ""

  // 添加用户消息
  chatMessages.value.push({
    role: "human",
    content: userMessage,
    time: new Date()
  })

  isLoading.value = true
  messagePlaceholder.value = ""

  try {
    // 生成会话ID（如果没有当前会话）
    if (!currentSessionId.value) {
      currentSessionId.value = String(Date.now())
    }

    // 准备发送数据，匹配后端的 ChatDTO 结构
    const chatData = {
      content: userMessage, // 使用content而不prompt
      userId: usersStore.userInfo?.id || 1,
      sessionId: currentSessionId.value, // 可选，后端会自动创建
      title: currentSessionId.value ? null : "新对话" // 新会话时设置标题
    }

    // 使用API发送消息
    const response = await apiSendMessage(chatData)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    // 处理流式响应
    const reader = response.body.getReader()
    const decoder = new TextDecoder("utf-8")
    let fullContent = ""

    while (true) {
      const { done, value } = await reader.read()

      if (done) break

      const chunk = decoder.decode(value, { stream: true })
      fullContent += chunk
      messagePlaceholder.value = fullContent
    }

    if (fullContent.trim()) {
      const content = processMarkdownContent(fullContent.trim())
      chatMessages.value.push({
        role: "system",
        content,
        time: new Date()
      })

      if (!currentSessionId.value) {
        await loadUserSessions()
      }

      messagePlaceholder.value = ""
    } else {
      chatMessages.value.push({
        role: "system",
        content: "抱歉，AI没有返回有效回复，请重试。",
        time: new Date()
      })
    }
  } catch (error) {
    ElMessage.error("发送消息失败")
    chatMessages.value.push({
      role: "system",
      content: "抱歉，消息发送失败，请检查网络连接或稍后重试。",
      time: new Date()
    })
  } finally {
    isLoading.value = false
  }
}

// 创建新会话（只是清空当前状态，实际会话在发送消息时创建）
const createNewChat = () => {
  currentSessionId.value = null // 清空当前会话ID
  chatMessages.value = [] // 清空消息列表
  ElMessage.success("已创建新对话，发送消息后会自动保存")
}

const switchSession = async sessionId => {
  currentSessionId.value = sessionId
  chatMessages.value = []

  // 加载历史消息
  try {
    const response = await getChatMessages(sessionId)

    if (response && response.data && Array.isArray(response.data)) {
      chatMessages.value = response.data.map(msg => ({
        role: msg.isAi ? "system" : "human",
        content: msg.content,
        time: new Date(msg.createdAt)
      }))
    }
  } catch (error) {
    ElMessage.error("加载历史消息失败")
  }
}

const handleQuickAction = action => {
  inputMessage.value = action.prompt
}

const handleKeydown = event => {
  // 中文输入法合成期不触发
  if (isComposing.value) return
  const isSubmitCombo = (event.ctrlKey || event.metaKey) && event.key === "Enter"
  const isPlainEnter = event.key === "Enter" && !event.shiftKey
  if (isSubmitCombo || isPlainEnter) {
    event.preventDefault()
    if (canSend.value) sendMessage()
  }
}

const formatTime = time => {
  if (!time) return ""
  const now = new Date()
  const messageTime = new Date(time)
  const diff = now - messageTime

  if (diff < 60000) return "刚刚"
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  return messageTime.toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" })
}

// 加载用户会话列表
const loadUserSessions = async () => {
  if (!usersStore.userInfo?.id) return

  try {
    loadingSessions.value = true
    const response = await getUserSessions(usersStore.userInfo.id)

    if (response && response.data) {
      sessions.value = response.data.map(session => ({
        id: session.sessionId,
        sessionId: session.sessionId,
        title: session.title,
        lastMessage: "点击查看对话",
        updatedAt: new Date(session.updatedAt || session.createdAt),
        messageCount: session.messageCount || 0
      }))
    }
  } catch (error) {
    ElMessage.error("加载会话列表失败")
  } finally {
    loadingSessions.value = false
  }
}

// 删除会话
const deleteSessionHandler = async sessionId => {
  if (!usersStore.userInfo?.id) return

  try {
    await deleteSession(sessionId, usersStore.userInfo.id)
    // 从本地列表中移除
    const index = sessions.value.findIndex(s => s.sessionId === sessionId)
    if (index > -1) {
      sessions.value.splice(index, 1)
    }
    // 如果删除的是当前会话，清空消息
    if (currentSessionId.value === sessionId) {
      currentSessionId.value = null
      chatMessages.value = []
    }
    ElMessage.success("会话删除成功")
  } catch (error) {
    ElMessage.error("删除会话失败")
  }
}

// 页面加载时获取会话列表
onMounted(() => {
  loadUserSessions()
})
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.chat-page {
  padding: $spacing-xl;
  background: $bg-color-layout;
  min-height: 100vh;
  @media (max-width: 768px) {
    padding: $spacing-md;
  }
}

.chat-container {
  height: calc(100vh - 64px - 2 * #{$spacing-xl});
  max-width: 1400px;
  margin: 0 auto;

  @media (max-width: 768px) {
    height: calc(100vh - 64px - 2 * #{$spacing-md});
  }
}

.chat-sidebar {
  @include theme-card;
  display: flex;
  flex-direction: column;

  .sidebar-header {
    background-color: transparent;
    border-color: var(--color-border-tertiary);

    .new-chat-btn {
      width: 100%;
      height: 44px;
      border-radius: $border-radius-base;
      font-weight: $font-weight-medium;
      font-size: $font-size-sm;
      background: $color-primary;
      border: none;
      box-shadow: none;
      transition: background-color 0.3s ease;

      &:hover {
        background: $color-primary-light-3;
        transform: none;
        box-shadow: none;
      }
    }
  }

  .session-list {
    padding: $spacing-md;

    .session-item {
      display: flex;
      align-items: center;
      padding: $spacing-base;
      cursor: pointer;
      border-radius: $border-radius-base;
      transition: background-color $transition-fast;
      margin-bottom: $spacing-sm;

      &:hover {
        background-color: var(--color-bg-hover);

        .session-actions .delete-btn {
          opacity: 1;
          visibility: visible;
        }
      }

      &.active {
        background-color: $color-primary-light-9;
        .session-title {
          color: $color-primary;
          font-weight: $font-weight-semibold;
        }

        .session-actions .delete-btn {
          opacity: 1;
          visibility: visible;
        }
      }

      .session-avatar {
        width: 40px;
        height: 40px;
        border-radius: $border-radius-base;
        background: linear-gradient(135deg, $color-primary-light-3, $color-primary);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: $spacing-base;
        flex-shrink: 0;
        font-size: $font-size-lg;
      }

      .session-content {
        flex: 1;
        min-width: 0;
        .session-title {
          font-size: $font-size-sm;
          color: $color-text-primary;
          margin-bottom: $spacing-xs;
          font-weight: $font-weight-medium;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .session-preview {
          font-size: $font-size-xs;
          color: $color-text-tertiary;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }

      .session-actions {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: $spacing-xs;
        flex-shrink: 0;
        min-width: 60px;

        .session-time {
          font-size: $font-size-xs;
          color: $color-text-quaternary;
          white-space: nowrap;
        }

        .delete-btn {
          opacity: 0;
          visibility: hidden;
          transition: all $transition-fast;
          width: 24px;
          height: 24px;
          min-height: 24px;
          padding: 0;
          border: none;
          background: transparent;
          color: $color-text-quaternary;

          &:hover {
            background: var(--color-danger-lighter);
            color: var(--color-danger);
            transform: scale(1.1);
          }

          &:focus {
            opacity: 1;
            visibility: visible;
          }

          .el-icon {
            font-size: 14px;
          }
        }
      }
    }
  }
}

.chat-main {
  @include theme-card;
  display: flex;
  flex-direction: column;
  min-height: 0;

  .chat-content {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    padding: $spacing-lg;
    background: $bg-color-layout;

    .empty-state,
    .messages-area {
      flex: 1;
      min-height: 0;
    }

    .empty-state {
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .messages-area {
      overflow-y: auto;
    }
  }

  .chat-footer {
    background: var(--color-bg-primary);
    border-top: 1px solid var(--color-border-tertiary);
  }

  .input-area {
    position: relative;
    padding: 0; // The wrapper will handle padding
  }

  .input-wrapper {
    position: relative;
    padding: $spacing-base;
    border: 1px solid var(--color-border-secondary);
    border-radius: $border-radius-base;
    transition: border-color $transition-fast;

    &:focus-within {
      border-color: $color-primary;
      box-shadow: 0 0 0 2px $color-primary-light-8;
    }
  }

  .send-button {
    position: absolute;
    right: $spacing-sm;
    top: 50%;
    transform: translateY(-50%);
    width: 32px;
    height: 32px;
    z-index: 1;

    .el-icon {
      font-size: 16px;
    }
  }

  .message-input {
    :deep(.el-textarea__inner) {
      border: none;
      padding: 0; // Padding is now on the wrapper
      padding-right: 40px; // Space for the button
      font-size: $font-size-sm;
      line-height: $line-height-normal;
      resize: none;
      min-height: 24px; // Adjusted for line-height
      max-height: 120px;
      background: transparent;
      box-shadow: none;

      &:focus {
        box-shadow: none;
      }
    }

    // 确保覆盖Element Plus的默认样式
    :deep(.el-textarea) {
      .el-textarea__inner {
        min-height: 24px;
      }
    }
  }

  .input-footer {
    padding: $spacing-xs $spacing-xl $spacing-base;
    text-align: center;
    background: var(--color-bg-primary);
    .disclaimer {
      font-size: $font-size-xs;
      color: $color-text-quaternary;
    }
  }
}

// 统一的 welcome 样式
.welcome-container {
  text-align: center;
  max-width: 600px;

  .ai-avatar {
    width: 80px;
    height: 80px;
    background: $color-primary-light-9;
    border-radius: $border-radius-lg;
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 auto 24px;
    color: $color-primary;
    font-size: 36px;
  }

  .welcome-title {
    font-size: 28px;
    color: $color-text-primary;
    margin-bottom: 12px;
    font-weight: 600;
  }

  .welcome-subtitle {
    color: $color-text-secondary;
    margin-bottom: 32px;
    font-size: 15px;
  }

  .quick-actions {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
    gap: 16px;
    max-width: 480px;
    margin: 0 auto;

    .quick-action-card {
      @include theme-card;
      padding: 16px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.2s ease-in-out;
      text-align: center;

      &:hover {
        transform: translateY(-2px);
        box-shadow: $box-shadow-sm;
        border-color: $color-primary-light-7;

        .action-icon {
          background: $color-primary;
          color: white;
        }
      }

      .action-icon {
        width: 40px;
        height: 40px;
        background: $bg-color-hover;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 12px;
        color: $color-primary;
        font-size: 20px;
        transition: all 0.3s ease;
      }

      .action-text {
        font-size: 14px;
        color: $color-text-primary;
        font-weight: 500;
      }
    }
  }
}

// 统一消息气泡样式
.message-wrapper {
  margin-bottom: $spacing-xl;
  display: flex;
  align-items: flex-start;
  max-width: 90%;

  &.human {
    justify-content: flex-end;
    margin-left: auto;

    .message-bubble {
      background: $color-primary;
      color: white;
      border-radius: 12px 12px 4px 12px;
      .user-message {
        white-space: pre-wrap;
        word-break: break-word;
      }
      .message-time {
        color: rgba(255, 255, 255, 0.7);
      }
    }
  }

  &.system {
    justify-content: flex-start;

    .message-bubble {
      @include theme-message-bubble;
      border-radius: 12px 12px 12px 4px;

      &.typing {
        .typing-indicator {
          display: flex;
          gap: 4px;
          margin-top: 8px;
          align-items: center;
          span {
            width: 6px;
            height: 6px;
            background: $color-primary;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
          }
          span:nth-child(2) {
            animation-delay: 0.2s;
          }
          span:nth-child(3) {
            animation-delay: 0.4s;
          }
        }
      }
    }
  }

  .message-bubble {
    padding: $spacing-base $spacing-md;
    position: relative;
    word-wrap: break-word;
    overflow-wrap: break-word;
    transition: all $transition-fast;
    box-shadow: $box-shadow-xs;

    .message-text {
      line-height: 1.6;
      font-size: $font-size-sm;

      :deep(pre) {
        background-color: $bg-color-hover !important;
        border-radius: $border-radius-base;
        padding: $spacing-md;
        margin: $spacing-md 0;
        overflow-x: auto;
        font-family: $font-family-code !important;
        border: 1px solid $border-color-extra-light;
      }
    }
    .message-time {
      font-size: $font-size-xs;
      color: $color-text-quaternary;
      margin-top: $spacing-sm;
      text-align: right;
    }
  }
}

@keyframes typing {
  0%,
  60%,
  100% {
    transform: scale(1);
    opacity: 0.5;
  }
  30% {
    transform: scale(1.3);
    opacity: 1;
  }
}

// ===== 响应式优化 =====
@media (max-width: 768px) {
  .chat-container {
    .layout-two-col {
      grid-template-columns: 1fr;

      .chat-sidebar {
        order: 2;
        max-height: 200px;

        .session-list {
          .session-item {
            padding: $spacing-sm;

            .session-avatar {
              width: 32px;
              height: 32px;
              font-size: $font-size-base;
            }

            .session-actions {
              min-width: 50px;

              .session-time {
                font-size: $font-size-xs;
              }

              .delete-btn {
                opacity: 1;
                visibility: visible;
                width: 20px;
                height: 20px;

                .el-icon {
                  font-size: 12px;
                }
              }
            }
          }
        }
      }

      .chat-main {
        order: 1;
      }
    }
  }
}

@media (max-width: 576px) {
  .chat-page {
    padding: $spacing-md;
  }

  .layout-two-col {
    gap: $spacing-md;
  }

  .session-item {
    .session-content {
      .session-title {
        font-size: $font-size-xs;
      }

      .session-preview {
        display: none;
      }
    }

    .session-actions {
      .session-time {
        display: none;
      }
    }
  }
}
</style>
